package com.alibaba.citrus.cr.price.ability.functions.entity.activity;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.citrus.cr.price.repository.ActivityQueryRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.domian.activitytitleext.model.ActivityTitleExt;
import com.epoch.app.crforecastsales.domian.activitytitleext.service.ActivityTitleExtService;
import com.epoch.app.crforecastsales.model.dto.ActivityTitleExtCreateRequest;
import com.epoch.app.crforecastsales.ofsactivitytermindex.dto.*;
import com.epoch.app.crpricecenter.dto.response.ActivityViewResponse;
import com.epoch.app.crpricecenter.model.dto.ActivityTermIndexSDO;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author hanguo
 * @date 2021/11/3
 * @Description 营销活动 ES 实体
 */
@Data
public class ActivityTermIndexEntity {

    private static Log log = Log.getLogger(ActivityTermIndexEntity.class);

    /**
     * 活动查询资源库
     */
    private static ActivityQueryRepository queryRepository = SpringContextUtil.getBean(ActivityQueryRepository.class);
    private static ActivityTitleExtService activityTitleExtService=SpringContextUtil.getBean(ActivityTitleExtService.class);

    private ActivityTermIndexSDO activityTermIndexSDO;


    public static ActivityTermIndexEntity of(ActivityTermIndexSDO activityTermIndexSDO) {
        ActivityTermIndexEntity activityTermIndexEntity = new ActivityTermIndexEntity();
        activityTermIndexEntity.setActivityTermIndexSDO(activityTermIndexSDO);
        return activityTermIndexEntity;


    }

    public Result<List<ActivityViewResponse>> queryPromotionPageList() {

        QueryPageActivityTermIndexResponse queryPageActivityTermIndexResponse = queryRepository.queryPromotionPageList(this.activityTermIndexSDO);

        if (Objects.isNull(queryPageActivityTermIndexResponse) || CollectionUtils.isEmpty(queryPageActivityTermIndexResponse.getResult())) {
            return Result.success(null);
        }

//        List<OfsActivityTermIndexLoadListVO> ofsActivityTermIndexLoadListVOS = JSONObject.parseArray(JSONObject.toJSONString(queryPageActivityTermIndexResponse.getResult()), OfsActivityTermIndexLoadListVO.class);


        List<ActivityViewResponse> activityViewResponses = queryPageActivityTermIndexResponse.getResult().stream().map(item -> {
            ActivityViewResponse activityViewResponse = new ActivityViewResponse();
            activityViewResponse.setSubId(item.getSubId());
            activityViewResponse.setActivityId(item.getSubActivityId());
            activityViewResponse.setActivityTermId(item.getSubActivityTermId());
            activityViewResponse.setSubVersion(item.getSubVersion() == null ? null : Integer.parseInt(item.getSubVersion().toString()));
            activityViewResponse.setMainVersion(item.getMainVersion() == null ? null : Integer.parseInt(item.getMainVersion().toString()));
            //先显示编码，后面再处理
            activityViewResponse.setSalesOrganizationDesc(item.getMainSalesOrganization());
            activityViewResponse.setChannelDesc(item.getMainSalesChannel());
            activityViewResponse.setClientDesc(item.getMainClientId());
            activityViewResponse.setItemDesc(item.getSubItemId());
            activityViewResponse.setGiftDesc(item.getSubGiftId());
            activityViewResponse.setBrandDesc(item.getSubBrand());
            activityViewResponse.setBrandCategoryDesc(item.getSubItemCategory());
            activityViewResponse.setBrandSubjectDesc(item.getSubItemSubject());
            activityViewResponse.setActivityNoteId(item.getMainActivityNoteId());
            activityViewResponse.setActivityNoteDesc(item.getMainActivityNoteName());
            activityViewResponse.setActivityStatus(item.getSubStatus() == null ? null : item.getSubStatus().toString());
            activityViewResponse.setOrderStartDate(DateUtils.toDateStr(item.getMainOrderStartDate(), "yyyy-MM-dd"));
            activityViewResponse.setOrderEndDate(DateUtils.toDateStr(item.getMainOrderEndDate(), "yyyy-MM-dd"));
            activityViewResponse.setActivityStartDate(DateUtils.toDateStr(item.getMainActivityStartDate(), "yyyy-MM-dd"));
            activityViewResponse.setActivityEndDate(DateUtils.toDateStr(item.getMainActivityEndDate(), "yyyy-MM-dd"));
            activityViewResponse.setItemQuantity(item.getSubItemQuantity() == null ? null : item.getSubItemQuantity().toString());
            activityViewResponse.setGiftQuantity(item.getSubGiftQuantity() == null ? null : item.getSubGiftQuantity().toString());
            String subSpecialOfferPrice = item.getSubSpecialOfferPrice();
            if (StringUtils.isNotBlank(subSpecialOfferPrice)) {
                activityViewResponse.setSpecialOfferPrice(new BigDecimal(subSpecialOfferPrice.trim()).divide(new BigDecimal(100)).toString());
            }
            //activityViewResponse.setSpecialOfferPrice(item.getSubSpecialOfferPrice());
            activityViewResponse.setUnitDesc(item.getSubSalesUnit());
            activityViewResponse.setActivityFacadeDesc(item.getSubFacadeDescription());
            activityViewResponse.setApplyItemQuantity(item.getSubApplyItemQuantity() == null ? null : item.getSubApplyItemQuantity().toString());
            Long subApplyFee = item.getSubApplyFee();
            if (Objects.nonNull(subApplyFee)) {
                activityViewResponse.setApplyFee(new BigDecimal(subApplyFee).divide(new BigDecimal(100)).toString());
            }
            Long subActivityOccupyFee = item.getSubActivityOccupyFee();
            if (Objects.nonNull(subActivityOccupyFee)) {
                activityViewResponse.setActivityOccurrenceFee(new BigDecimal(subActivityOccupyFee).divide(new BigDecimal(100)).toString());
            }
            activityViewResponse.setControlByGroupFlag(item.getMainControlByGroupFlag());
            activityViewResponse.setActivityTypeDesc(item.getMainActivityFacadeCode());
            activityViewResponse.setActivityOccurrence(item.getSubActivityOccupyQuantity() == null ? null :
                    item.getSubActivityOccupyQuantity().toString());
            activityViewResponse.setActivityRemaining(null);
            //活动申请量
            Long activityApplyItemQuantity = item.getSubApplyItemQuantity();
            //活动占用量
            Long activityOccupyQuantity = item.getSubActivityOccupyQuantity();
            //设置活动剩余量
            if (Objects.nonNull(activityApplyItemQuantity) && Objects.nonNull(activityOccupyQuantity)) {
                Long activityRemaining = activityApplyItemQuantity - activityOccupyQuantity;
                activityViewResponse.setActivityRemaining(activityRemaining.toString());
            }
            //设置总部投入金额
            Long subHeadQuartersInvestMoney = item.getSubHeadQuartersInvestMoney();
            if (Objects.nonNull(subHeadQuartersInvestMoney)) {
                activityViewResponse.setHeadQuartersInvestMoney(new BigDecimal(subHeadQuartersInvestMoney).divide(new BigDecimal(100)).toString());
            }

            //设置公司自投金额
            Long subCompanySelfInvestMoney = item.getSubCompanySelfInvestMoney();
            if (Objects.nonNull(subCompanySelfInvestMoney)) {
                activityViewResponse.setCompanySelfInvestMoney(new BigDecimal(subCompanySelfInvestMoney).divide(new BigDecimal(100)).toString());
            }
            activityViewResponse.setActivityRemainingFee(null);
            //活动申请费用
            Long activityApplyItemFee = item.getSubApplyFee();
            //活动占用费用
            Long activityOccupyFee = item.getSubActivityOccupyFee();
            //设置活动剩余费用
            if (Objects.nonNull(activityApplyItemFee) && Objects.nonNull(activityOccupyFee)) {
                BigDecimal activityRemainingFee = new BigDecimal(activityApplyItemFee - activityOccupyFee);
                activityViewResponse.setActivityRemainingFee(activityRemainingFee.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).toString());
            }

            //如果是按组管控，填充ext表相关的便签活动数据
            if (StringUtils.isNotBlank(item.getMainControlByGroupFlag()) && "X".equals(item.getMainControlByGroupFlag())) {


                String activityNoteId = item.getMainActivityNoteId();
                ActivityTitleExtCreateRequest activityTitleExtCreateRequest = new ActivityTitleExtCreateRequest();
                activityTitleExtCreateRequest.setActivityNoteId(activityNoteId);
                ActivityTitleExt activityTitleExt = activityTitleExtService.queryActivityTitleExt(activityTitleExtCreateRequest);
                if (Objects.nonNull(activityTitleExt)) {
                    Long noteApplyQuantity = Nullable.of(activityTitleExt.getApplyItemQuantity()).orElse(0L);
                    Long noteOccupyQuantity = Nullable.of(activityTitleExt.getActivityOccupyQuantity()).orElse(0L);
                    Long noteApplyFee = Nullable.of(activityTitleExt.getApplyFee()).orElse(0L);
                    Long noteOccupyFee = Nullable.of(activityTitleExt.getActivityOccupyFee()).orElse(0L);
                    long activityRemainQuantity = noteApplyQuantity - noteOccupyQuantity;
                    long activityRemainFee = noteApplyFee - noteOccupyFee;
                    activityViewResponse.setNoteApplyQuantity(String.valueOf(noteApplyQuantity));
                    activityViewResponse.setNoteApplyFee(String.valueOf(new BigDecimal(noteApplyFee).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP)));
                    activityViewResponse.setNoteoccupyQuantity(String.valueOf(noteOccupyQuantity));
                    activityViewResponse.setNoteOccupyFee(String.valueOf(new BigDecimal(noteOccupyFee).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP)));
                    activityViewResponse.setNoteRemainQuantity(String.valueOf(activityRemainQuantity));
                    activityViewResponse.setNoteRemainFee(String.valueOf(new BigDecimal(activityRemainFee).divide(new BigDecimal("100"),2,RoundingMode.HALF_UP)));
                }



            }
            return activityViewResponse;
        }).collect(Collectors.toList());

        Result<List<ActivityViewResponse>> result = Result.success(activityViewResponses);

        result.setTotal(queryPageActivityTermIndexResponse.getTotal());

        return result;
    }


    public Result<List<String>> queryCustomerIds() {
        Integer total;
        this.activityTermIndexSDO.setLimit(20);
        List<String> clientList = Lists.newArrayList();
        do {
            QueryClientIdsResponse queryClientIdsResponse = queryRepository.queryCustomerIds(this.activityTermIndexSDO);
            if (Objects.isNull(queryClientIdsResponse) || CollectionUtils.isEmpty(queryClientIdsResponse.getResult())) {
                total = 0;
            } else {
                total = 1;
                clientList.addAll(queryClientIdsResponse.getResult());
                this.activityTermIndexSDO.setStart(this.activityTermIndexSDO.getStart() + this.activityTermIndexSDO.getLimit());
            }
        } while (total > 0);

        Result<List<String>> result = Result.success(clientList);
        result.setTotal(clientList.size());
        return result;
    }

    public Result<List<String>> querySaleOrganizationIds() {
        this.activityTermIndexSDO.setLimit(20);
        Integer total;
        List<String> salesOrganizationList = Lists.newArrayList();
        do {
            QuerySalesOrganizationIdsResponse querySalesOrganizationIdsResponse = queryRepository.querySalesOrganizationIds(this.activityTermIndexSDO);
            if (Objects.isNull(querySalesOrganizationIdsResponse) || CollectionUtils.isEmpty(querySalesOrganizationIdsResponse.getResult())) {
                total = 0;
            } else {
                total = 1;
                salesOrganizationList.addAll(querySalesOrganizationIdsResponse.getResult());
                this.activityTermIndexSDO.setStart(this.activityTermIndexSDO.getStart() + this.activityTermIndexSDO.getLimit());
            }

        } while (total > 0);

        Result<List<String>> result = Result.success(salesOrganizationList);
        result.setTotal(salesOrganizationList.size());
        return result;
    }

    public Result<List<String>> queryChannelIds() {
        Integer total;
        this.activityTermIndexSDO.setLimit(20);
        List<String> channelList = Lists.newArrayList();
        do {
            QueryChannelIdsResponse queryChannelIdsResponse = queryRepository.queryChannelIds(this.activityTermIndexSDO);
            if (Objects.isNull(queryChannelIdsResponse) || CollectionUtils.isEmpty(queryChannelIdsResponse.getResult())) {
                total = 0;
            } else {
                total = 1;
                channelList.addAll(queryChannelIdsResponse.getResult());
                this.activityTermIndexSDO.setStart(this.activityTermIndexSDO.getStart() + this.activityTermIndexSDO.getLimit());
            }
        } while (total > 0);

        Result<List<String>> result = Result.success(channelList);
        result.setTotal(channelList.size());
        return result;
    }

    public Result<List<String>> queryItemIds() {

        Integer total;
        this.activityTermIndexSDO.setLimit(20);
        List<String> itemList = Lists.newArrayList();
        do {
            QueryItemIdsResponse queryItemIdsResponse = queryRepository.queryItemIds(this.activityTermIndexSDO);
            if (Objects.isNull(queryItemIdsResponse) || CollectionUtils.isEmpty(queryItemIdsResponse.getResult())) {
                total = 0;
            } else {
                total = 1;
                itemList.addAll(queryItemIdsResponse.getResult());
                this.activityTermIndexSDO.setStart(this.activityTermIndexSDO.getStart() + this.activityTermIndexSDO.getLimit());
            }

        } while (total > 0);

        Result<List<String>> result = Result.success(itemList);
        result.setTotal(itemList.size());
        return result;
    }
}
